﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OctoOS.UI;
using OctoOS;
using OctoOS.Services;

public partial class adInfo : OOSPage
{
    class PathInfo
    {
        [PathInfoMember(0)]
        internal long adID;

        [PathInfoMember(1, true)]
        internal int pageIndex;
    }

    PathInfo _pathInfo;
    ClassifiedAd _ad = null;

    protected void Page_Init(object sender, EventArgs e)
    {
        _pathInfo = EnablePathInfo<PathInfo>();
        Helper.Categories.UpdateCategoryCache();
    }

    protected void Page_Load(object sender, EventArgs e)
    {

        threadView.GroupID = OOSRequest.Current.ResourceID;
        threadView.ThreadID = _pathInfo.adID;
        threadView.PageUrlPattern = "/company.aspx/" + _pathInfo.adID + "/{0}";
        threadView.FirstPageUrl = "/company.aspx/" + _pathInfo.adID;
        if (_pathInfo.pageIndex != 0)
        {
            threadView.PageIndex = _pathInfo.pageIndex - 1;
        }

        
        _ad = DataSource.ClassifiedAds_GetByID(
            OOSRequest.Current.ResourceID,
            0,
            _pathInfo.adID);
        if (_ad != null)
        {
            SetBreadcrumbs();
            if (_ad.ExpiryTime > DateTime.Today)
            {
                if (OOSRequest.Current.IsModerator || (_ad.UserID != 0 && _ad.UserID == OOSRequest.Current.UserID))
                {
                    AddAction("Delete ad", Urls.Classifieds.GetAdsDelete(_pathInfo.adID));
                    AddAction("Edit Ad", Urls.Classifieds.GetEditAd(_pathInfo.adID));
                }
                AddAction("Abuse Ad", Urls.Classifieds.GetAdAbuse(_pathInfo.adID));
            }
            PageTitle = _ad.Title;
            Author.Text = _ad.UserID == 0 ? "Anonymous" : _ad.UserID.ToString();
            Category.Text = GetAdCategory();
            Title.Text = _ad.Title;
            AdText.Text = _ad.AdText;
            PostTime.Text = _ad.PostTime.ToShortDateString();
            ExpiryTime.Text = _ad.ExpiryTime.ToShortDateString();
            Latitude.Text = _ad.Latitude == 0 ? "not defined" : _ad.Latitude.ToString();
            Longitude.Text = _ad.Longitude == 0 ? "not defined" : _ad.Longitude.ToString();
            PriceType.Text = _ad.PriceType == 0 ? "Free" :
                _ad.PriceType == 0 ? "Please contact" : "Money";
            Price.Text = _ad.Price.ToString("F2")+ " "+_ad.CurrencyCode;
            AdType.Text = _ad.Searching == false ? "Offer" : "Need";
            Phone.Text = _ad.ContactPhone;
            Mail.Text = _ad.ContactEMail;
            Url.Text = _ad.ContactUrl;

            if (_ad.Status == (byte)Helper.AdStatus.Declined)
            {
                AdminView.Visible = true;
                MessageText.Text = _ad.StatusDescription;
                threadView.Visible = false;
                postForm.Visible = false;
            }

            switch (_ad.Comments)
            {
                case (byte)Helper.Comments.AuthenticateOnly:
                    if (OOSRequest.Current.UserID == 0)
                    {
                        postForm.Visible = false;
                    }
                    break;
                case (byte)Helper.Comments.Disabled:
                    postForm.Visible = false;
                    break;
            }
            foreach (var attribute in _ad.Attributes.OrderByDescending(f=>f.SortOrder))
            {
                // if there is choosen value
                if (!attribute.IsCustom)
                {
                    if (attribute.AttributeValues.Where(f => f.Selected == true).Count() > 0)
                    {
                        FormRow row = new FormRow();
                        row.Label = attribute.Title;
                        var value = attribute.AttributeValues.FirstOrDefault(f => f.Selected == true);
                        if (value != null)
                        {
                            OctoOS.UI.Literal lit = new OctoOS.UI.Literal(value.AttributeValueName);
                            row.Controls.Add(lit);
                            FormView.Controls.AddAt(FormView.Controls.IndexOf(FormView.FindControl("LongitudeRow"))+1,row);
                        }
                        else
                        {
                            break;
                        }

                    }
                }
                else
                {
                    if (attribute.AttributeValues.Count() > 0)
                    {
                        FormRow row = new FormRow();
                        row.Label = attribute.Title;
                        OctoOS.UI.Literal lit = new OctoOS.UI.Literal(attribute.AttributeValues[0].AttributeValueName);
                        row.Controls.Add(lit);
                        FormView.Controls.AddAt(FormView.Controls.IndexOf(FormView.FindControl("LongitudeRow")) + 1, row);
                    }
                }
            }
        }
        else
        {
            throw new HttpException(404, "This page is not found");
        }
    }

    private void SetBreadcrumbs()
    {
        AddBreadcrumb(string.Empty, "/");
        Category current = Helper.Categories.GetCategory(_ad.CategoryID);
        Category parent = Helper.Categories.GetParentCategory(_ad.CategoryID);
        Category grandParent = Helper.Categories.GetGrandParentCategory(_ad.CategoryID);
        if (grandParent != null)
        {
            AddBreadcrumb(grandParent.Name, Urls.Classifieds.GetCategoryInfo(grandParent.ID));
        }
        if (parent != null)
        {
            AddBreadcrumb(parent.Name, Urls.Classifieds.GetCategoryInfo(parent.ID));
        }
        if (current != null)
        {
            AddBreadcrumb(current.Name, Urls.Classifieds.GetCategoryInfo(current.ID));
        }
    }

    private string GetAdCategory()
    {
        string result = "Uncategorized";

        Category currentCategory = Helper.Categories.GetCategory(_ad.CategoryID);
        Category parentCategory = Helper.Categories.GetParentCategory(_ad.CategoryID);
        Category grandParentCategory = Helper.Categories.GetGrandParentCategory(_ad.CategoryID);
        if (grandParentCategory != null)
        {
            result = grandParentCategory.Name + " - ";
        }
        if (parentCategory != null)
        {
            result += parentCategory.Name + " - ";
        }
        if (currentCategory != null)
        {
            result += currentCategory.Name;
        }
        return result;
    }

    protected void SubmitPost(object sender, EventArgs e)
    {
        if (IsValid)
        {
            OOSRequest oosRequest = OOSRequest.Current;

            long postID;
            ICommentService srv = ServiceFactory.GetService<ICommentService>();
            using (srv as IDisposable)
            {
                postID = srv.AddPost(oosRequest.Token, oosRequest.ResourceID,
                 threadView.GroupID, threadView.ThreadID, 0, postForm.Author, "", postForm.Message, TextFormat.Plain);
            }

            Response.Redirect(Urls.Classifieds.GetPostRedirectUrl(threadView.ThreadID, postID));
        }
    }
}